{
 "cells": [
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "# 排序算法\n",
    "\n",
    "## 目录\n",
    "- 插入排序\n",
    "- 交换排序\n",
    "- 选择排序\n",
    "- 归并排序\n",
    "- 基数排序\n",
    "- Timsort\n",
    "\n",
    "| 算法                      | 平均时间复杂度 | 最好情况时间复杂度 | 最坏情况时间复杂度 | 空间复杂度 | 是否稳定 |\n",
    "| ------------------------- | -------------- | ------------------ | ------------------ | ---------- | -------- |\n",
    "| 冒泡排序 (Bubble Sort)    | O(n^2)         | O(n)               | O(n^2)             | O(1)       | 是       |\n",
    "| 选择排序 (Selection Sort) | O(n^2)         | O(n^2)             | O(n^2)             | O(1)       | 否       |\n",
    "| 插入排序 (Insertion Sort) | O(n^2)         | O(n)               | O(n^2)             | O(1)       | 是       |\n",
    "| 快速排序 (Quick Sort)     | O(n log n)     | O(n log n)         | O(n^2)             | O(log n)   | 否       |\n",
    "| 归并排序 (Merge Sort)     | O(n log n)     | O(n log n)         | O(n log n)         | O(n)       | 是       |\n",
    "| 堆排序 (Heap Sort)        | O(n log n)     | O(n log n)         | O(n log n)         | O(1)       | 否       |\n",
    "| 希尔排序 (Shell Sort)     | 取决于步长序列 | O(n log^2 n)       | O(n (log n)^2)     | O(1)       | 否       |\n",
    "| 计数排序 (Counting Sort)  | O(n + k)       | O(n + k)           | O(n + k)           | O(k)       | 是       |\n",
    "| 桶排序 (Bucket Sort)      | O(n + k)       | O(n^2)             | O(n^2)             | O(n + k)   | 是       |\n",
    "| 基数排序 (Radix Sort)     | O(d(n + k))    | O(d(n + k))        | O(d(n + k))        | O(n + k)   | 是       |\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "## 1. 插入排序\n",
    "\n",
    "插入排序是一种简单直观的排序算法, 基本思想是每次将一个待排序的记录按其关键字的大小插入到前面已经排好的子序列中, 知道全部记录插入完毕\n",
    "\n",
    "\n",
    "\n",
    "### 1.1 直接插入排序\n",
    "\n",
    "可以类比于扑克牌的抽牌过程, 由于需要不停地移动表内元素的位置, 所以效率较差, 其时间复杂度为O(n^2), 是一个稳定的排序算法"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[85, 63, 51, 26, 30, 4, 7, 1, 17, 81, 64, 91, 50, 60, 97, 72, 63, 54, 55, 93, 27, 81, 67, 0, 39, 85, 55, 3, 76, 72, 84, 17, 8, 86, 2, 54, 8, 29, 48, 42, 40, 2, 0, 12, 0, 67, 52, 64, 25, 61, 76, 38, 46, 99, 80, 98, 37, 68, 95, 65]\n"
     ]
    }
   ],
   "source": [
    "# 使用numpy 生成一个待排序的随机数组\n",
    "import numpy as np\n",
    "\n",
    "rng = np.random.default_rng(0)\n",
    "a = rng.integers(0, 100, size=60).tolist()\n",
    "print(a)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[0, 0, 0, 1, 2, 2, 3, 4, 7, 8, 8, 12, 17, 17, 25, 26, 27, 29, 30, 37, 38, 39, 40, 42, 46, 48, 50, 51, 52, 54, 54, 55, 55, 60, 61, 63, 63, 64, 64, 65, 67, 67, 68, 72, 72, 76, 76, 80, 81, 81, 84, 85, 85, 86, 91, 93, 95, 97, 98, 99]\n"
     ]
    }
   ],
   "source": [
    "def insertion_sort(arr):\n",
    "    # 遍历数组等于抽牌, 第i个元素就是抽到的i张牌, 第一个不用排序, 因为等于抽到的第一张牌\n",
    "    for i in range(1, len(arr)):\n",
    "        v = arr[i]  # 当前抽到牌的值\n",
    "        j = i - 1  # 抽到的牌需要插入的位置\n",
    "        while arr[j] > v and j >= 0:\n",
    "            arr[j + 1] = arr[j]  # 给要新插入的牌腾个位置\n",
    "            j -= 1\n",
    "        arr[j + 1] = v\n",
    "\n",
    "    return arr\n",
    "\n",
    "\n",
    "print(insertion_sort(a))"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "### 1.2 折半插入排序\n",
    "\n",
    "折半插入排序是一种在直接插入排序算法上略微优化的排序算法, 主要利用在抽牌阶段前面的i位为有序的数组, 所以利用二分法查找需要插入的位置"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[0, 0, 0, 1, 2, 2, 3, 4, 7, 8, 8, 12, 17, 17, 25, 26, 27, 29, 30, 37, 38, 39, 40, 42, 46, 48, 50, 51, 52, 54, 54, 55, 55, 60, 61, 63, 63, 64, 64, 65, 67, 67, 68, 72, 72, 76, 76, 80, 81, 81, 84, 85, 85, 86, 91, 93, 95, 97, 98, 99]\n"
     ]
    }
   ],
   "source": [
    "def binary_insertion_sort(arr):\n",
    "    for i in range(1, len(arr)):\n",
    "        v = arr[i]\n",
    "        hi = i - 1\n",
    "        lo = 1\n",
    "        while lo <= hi:\n",
    "            mid = (hi + lo) // 2\n",
    "            if arr[mid] > v:\n",
    "                hi = mid - 1\n",
    "            else:\n",
    "                lo = mid + 1\n",
    "        for j in range(i, lo, -1):\n",
    "            arr[j] = arr[j - 1]\n",
    "\n",
    "        arr[lo] = v\n",
    "\n",
    "\n",
    "print(insertion_sort(a))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "4.48 µs ± 184 ns per loop (mean ± std. dev. of 7 runs, 3,000 loops each)\n"
     ]
    }
   ],
   "source": [
    "%timeit -n 3000 -r 7 insertion_sort(a)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "28.3 µs ± 1.16 µs per loop (mean ± std. dev. of 7 runs, 3,000 loops each)\n"
     ]
    }
   ],
   "source": [
    "%timeit -n 3000 -r 7 binary_insertion_sort(a)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "290 ns ± 4.08 ns per loop (mean ± std. dev. of 7 runs, 3,000 loops each)\n"
     ]
    }
   ],
   "source": [
    "%timeit -n 3000 -r 7 sorted(a)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
